package com.hmall.service;


import com.hdmall.business.common.common.ServerResponse;
import com.hmall.util.CastHotUtil;
import com.hdmall.business.common.util.SimilarUtil;
import com.hmall.vo.*;
import com.hmall.model.BigList;
import com.hmall.mapper.*;
import com.hmall.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;

@Service
public class ProductClassService {

    //数据库中父节点11代表着锦纶
    private static final int PARENT_ID = 6;

    private static final int SUCCESS = 50;


    CastHotUtil castHotUtil = new CastHotUtil();
    private final
    MallProductMapper mallProductMapper;

    private final
    MallPriceMapper mallPriceMapper;

    private final
    MallHistoryMapper mallHistoryMapper;

    private final
    MallHotMapper mallHotMapper;

    private final
    MallOrderMapper mallOrderMapper;

    private final
    MallOrderItemMapper mallOrderItemMapper;

    private final
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    public ProductClassService(MallPriceMapper mallPriceMapper, MallProductMapper mallProductMapper, MallAttrValueMapper mallAttrValueMapper, MallCatDdMapper mallCatDdMapper, MallAttrConnectMapper mallAttrConnectMapper, MallHistoryMapper mallHistoryMapper, MallHotMapper mallHotMapper, MallOrderMapper mallOrderMapper, MallOrderItemMapper mallOrderItemMapper, SysUserTempMapper userTempMapper, SysUserRoleMapper sysUserRoleMapper) {
        this.mallPriceMapper = mallPriceMapper;
        this.mallProductMapper = mallProductMapper;
        this.mallHistoryMapper = mallHistoryMapper;
        this.mallHotMapper = mallHotMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
    }


    public ServerResponse<PageVo<ShortCompete>> listComProduct(SysUser user, String typeName, String fineAndPoreName, String glossName, String gradeName, Integer pageNum, Integer pageSize) {


        //获得独立的纤度和孔数 进行组合查询
        String fineName = null;
        String poreName = null;

        if(fineAndPoreName != null && fineAndPoreName.trim().length() > 2) {
             fineName = fineAndPoreName.split("/")[0];
             poreName = fineAndPoreName.split("/")[1];
            poreName = "/" + poreName;
        }


        //所查页数起始位置
        Integer pageStart = pageSize * (pageNum - 1);

        //总页数
        int total = mallProductMapper.selectCountData(typeName, fineName, poreName, glossName, gradeName);
        //分页查询
        List<Map<String, Object>> mapList = mallProductMapper.selectByPage(typeName, fineName, poreName, glossName, gradeName, pageStart, pageSize);

        //重新封装对象
        List<ShortCompete> shortCompeteList = new ArrayList<>();

        for(Map<String,Object> map : mapList) {
                ShortCompete shortCompete = new ShortCompete();

                //拼接到最后

               //属性
                int productId = (int) map.get("productId");
                String grade = (String) map.get("grade");

                String name = (String) map.get("name"); name = name + "," + grade;
                BigDecimal price = (BigDecimal) map.get("price");
                int isNew = (int) map.get("isNew");

                //装箱
                shortCompete.setProductId(productId);
                shortCompete.setName(name);
                shortCompete.setGrade(grade);

                SysUser noUser = new SysUser();
                //不登陆无法看到挂牌价
                if(user!=null) {
                    shortCompete.setPrice(price);
                }  else {
                    BigDecimal ZeroPrice = new BigDecimal(0);
                    shortCompete.setPrice(ZeroPrice);
                }

                shortCompete.setUnit("千克");
                shortCompete.setNew(isNew != 0);
                shortCompete.setStock((Integer) map.get("stock"));

                //如果资质不通过则只能看普通报价，资质通过能看所有的价格
                //资质通过状态为temp表中status为3


                //价格对应了等级
                List<MallPrice> mallPriceList = new ArrayList<>();

      //          Integer status = userTempMapper.queryStatus();


                mallPriceList = mallPriceMapper.findPriceAndGradeList(productId, grade);


                //如果找不到价格 不录入
                if(mallPriceList == null) {
                    return ServerResponse.createByStatus(22 , "商品找不到价格");
                }

            //如果用户登录并且已经是资质通过状态可以展示价格
            //如果用户只是登录可以通过price字段获取推荐价格
            //如果用户没登陆 什么价格都不展示
            shortCompete.setComPrice(new ArrayList<>());
                if(user!=null) {
                    SysUserRole userRole = sysUserRoleMapper.selectRole(user.getUserId());
                    int role = userRole.getRoleId();
                    //role 为2 普通用户 role为3 资质通过后的用户

                       if(role == 2){
                            for(MallPrice mallPrice : mallPriceList){
                                mallPrice.setPriceNum(new BigDecimal(0));
                            }
                        }

                        shortCompete.setComPrice(mallPriceList);

                }
                shortCompeteList.add(shortCompete);
            }

        PageVo<ShortCompete> pageVo = new PageVo<>(pageNum, pageSize, total, shortCompeteList);
      return ServerResponse.createBySuccess(pageVo);
    }



    //写死的，所有根据这个DTY/FDY/HOY来获得列表
    public ServerResponse<BigList> listBigList(String typeName) {

        //所有类型
        List<String> typeList = new ArrayList<>();

        //所有纤度和孔数
        List<String> fineAndPoreList = new ArrayList<>();

        //所有的光泽
        List<String> glossList = new ArrayList<>();

        //所有的等级
        List<String> gradeList = new ArrayList<>();

        typeList = mallProductMapper.listType(PARENT_ID);
        fineAndPoreList = mallProductMapper.listFineAndPore(typeName);
        glossList = mallProductMapper.listGloss(typeName);
        //将type在产品表里取查询得到所有的product_id 然后去price表里面查出等级

        List<Integer> productIdList = mallProductMapper.listProductIdByType(typeName);

        StringBuilder productIdStr = new StringBuilder();
        int index = 0;
        for(int productId : productIdList){
            if(index == 0) {
                productIdStr.append(String.valueOf(productId));
                index ++;
            }
            else productIdStr.append(",").append(String.valueOf(productId));
        }

        List<String> gradeByIdList = mallPriceMapper.findGradeListByProductIdStr(productIdList);
        System.out.println("gradeByIdList:" + gradeByIdList);

        Set<String> set = new HashSet<>(typeList);
        typeList.clear();
        typeList.addAll(set);

        set.clear();
        set.addAll(glossList);
        glossList.clear();
        glossList.addAll(set);

        set.clear();
        set.addAll(gradeList);
        gradeList.clear();
        gradeList.addAll(set);

        set.clear();


        int page = 1;
        StringBuilder strFineAndPore = null;
        List<String> strFineAndPoreList = new ArrayList<>();
        for (String str : fineAndPoreList) {
            if(page == 1){
                page = 2;
                strFineAndPore = new StringBuilder(str);
            } else{
                page = 1;
                strFineAndPore.append("/").append(str);
                strFineAndPoreList.add(strFineAndPore.toString());
                strFineAndPore = null;
            }
        }

        //去重纤度孔数
        set.clear();
        set.addAll(strFineAndPoreList);
        strFineAndPoreList.clear();
        strFineAndPoreList.addAll(set);

        //排序好纤度孔数顺序

        //String 改int
        List<FineAndPore> intFineAndPoreList = new ArrayList<>();
        for(String strFineAndPoreSub : strFineAndPoreList){
            String [] str = strFineAndPoreSub.split("/");
            int fine = Integer.valueOf(str[0]);
            int pore = Integer.valueOf(str[1]);
            intFineAndPoreList.add(new FineAndPore(fine, pore) );
        }



        //对结构排序
        intFineAndPoreList.sort((o1, o2) -> {
            if (o1.getFine() == o2.getFine()) {
                return o1.getPore() - o2.getPore();
            }
            return o1.getFine() - o2.getFine();
        });

        System.out.println(intFineAndPoreList);
        //重新得到串
        List<String> strFineAndPoreListRe = new ArrayList<>();
        for(FineAndPore fineAndPore : intFineAndPoreList){
            String strRe = fineAndPore.getFine() + "/" + fineAndPore.getPore();
            strFineAndPoreListRe.add(strRe);
        }
        Collections.sort(typeList);
        Collections.sort(glossList);
        Collections.sort(gradeByIdList);

        int[] arr = new int[10];
        arr[0] = 0;
        arr[1] = 40;
        arr[2] = 80;
        arr[3] = 120;
        arr[4] = 160;
        arr[5] = 200;

        List<FineAndPoreVo> fineAndPoreVoList = new ArrayList<>();

        int range = 0;

        while (++range < 6) {
            FineAndPoreVo fineAndPoreVo = new FineAndPoreVo();
            fineAndPoreVo.setStartLine(arr[range - 1]);
            fineAndPoreVo.setEndLine(arr[range]);

            int flag = 0;
            //遍历五次，可优化为只遍历一次
            List<String> strFineAndPoreListSon = new ArrayList<>();
            for (String strRe :strFineAndPoreListRe) {

                String [] spitStr = strRe.split("/");
                int fine = Integer.valueOf(spitStr[0]);
                if (fine > arr[range - 1] && fine < arr[range]) {
                    System.out.println(strRe);
                    strFineAndPoreListSon.add(strRe);
                    flag++;
                }
            }


            fineAndPoreVo.setFineAndPoreList(strFineAndPoreListSon);
            if (flag == 0) continue;
            fineAndPoreVoList.add(fineAndPoreVo);
        }

        BigList bigList = new BigList();
        bigList.setFineAndPoreVoList(fineAndPoreVoList);
        bigList.setGlossList(glossList);
        bigList.setGradeList(gradeByIdList);
        bigList.setTypeList(typeList);

        return ServerResponse.createBySuccess(bigList);


    }

    //产品详情
    public ServerResponse<ProductClassDetailVo> listProductDetail(Integer userId, Integer productId) {


        String title = "";

        MallProduct product = mallProductMapper.selectByProductId(productId);

        String name = product.getName();

        String[] str = name.split(",");
        title += str[0] + str[3] + str[4].substring(1, str[4].length()) + str[1];

        List<String> gradeList = mallPriceMapper.findGradeListByProductId(productId);


        Map<String, List<MallPrice>> price = new LinkedHashMap<>();
        //如果资质通过可以看价格
        SysUserRole userRole = new SysUserRole();
        int role = 0;
        if(userId != null) {
            System.out.println(userId);
            userRole = sysUserRoleMapper.selectRole(userId);

            role = userRole.getRoleId();
        }
        //role 为 2 表示普通用户 role为3 表示资质通过后的用户

            List<MallPrice> priceList = mallPriceMapper.findPriceList(productId);

            for (String grade : gradeList) {
                GradePriceVo gradePriceVo = new GradePriceVo();
                gradePriceVo.setGrade(grade);
               List<MallPrice> mallPriceList = new ArrayList<>();


                   mallPriceList = mallPriceMapper.findPriceListByProductIdAndGrade(productId, grade);

               if(role == 2)
                   for(MallPrice mallPrice : mallPriceList){
                        BigDecimal bigDecimal = new BigDecimal(0);
                        mallPrice.setPriceNum(bigDecimal);
               }
                price.put(grade, mallPriceList);
            }

            BigDecimal salesVolumne = mallHotMapper.selectSalesByProductId(productId);
            MallHotVo mallHotVo = CastHotUtil.hotCast(product, salesVolumne);
            return ServerResponse.createBySuccess(new ProductClassDetailVo(mallHotVo, price, title));
    }

    public ServerResponse<List<MallHotVo>> listHotPush(Integer hotCount, Integer shopId) {


        //就10条数据

        List<Map> mapList = mallHotMapper.listHotList(hotCount, shopId);


        List<MallHotVo> mallHotVoList = new ArrayList<>();
        for(Map map : mapList){
            MallHotVo mallHotVo = new MallHotVo();
            mallHotVo.setPrice((BigDecimal) map.get("price"));
            mallHotVo.setMainImage((String) map.get("main_image"));
            mallHotVo.setSales_volume((BigDecimal)map.get("sales_volume"));
            mallHotVo.setName((String) map.get("name"));
            mallHotVoList.add(mallHotVo);
        }

     return  ServerResponse.createBySuccess(mallHotVoList);
    }

    //相似度 计算公式
    public ServerResponse<List<MallHotVo>> listSimilarPush(Integer similarCount, Integer productId, Integer shopId) {

        //商家所有卖的产品
        //List<MallProduct> sellMallProductList = mallProductMapper.selectList();
        List<MallProduct> sellMallProductList = mallProductMapper.selectByShopId(shopId);

        //买的商品的属性
        MallProduct buyMallProduct = mallProductMapper.selectByProductId(productId);
        String buyName = buyMallProduct.getName();

        Map<MallProduct, Integer> map = new HashMap<>();

        for(MallProduct mallProduct : sellMallProductList){

            int value = SimilarUtil.similarValue(buyName, mallProduct.getName());
            map.put(mallProduct, value);
        }

        //进行排序
        List<Entry<MallProduct,Integer>> list = new ArrayList<>(map.entrySet());
        list.sort((o1, o2) -> o2.getValue() - o1.getValue());

        //转换成集合
        List<MallProduct> mallProductList = new ArrayList<>();
        for(Entry<MallProduct, Integer> t: list){
            mallProductList.add(t.getKey());
        }


        //取最相似的前similarCount数目的产品
        List<MallProduct> subMallProductList = new ArrayList<>();
        for(int i = 0; i < similarCount; i++){
            subMallProductList.add(mallProductList.get(i));
        }

        //就六个不用批量查询
        List<MallHotVo> mallHotVoList = new ArrayList<>();
        for(MallProduct mallProduct : subMallProductList){
            BigDecimal salesVolume = mallHotMapper.selectSalesByProductId(mallProduct.getId());
            mallHotVoList.add(CastHotUtil.hotCast(mallProduct,salesVolume));

        }

        return ServerResponse.createBySuccess(mallHotVoList);
    }

    //记录浏览记录
    public void recordView(Integer userId, Integer productId) {

        MallHistory mallHistory = new MallHistory();
        mallHistory.setUserid(userId);
        mallHistory.setProductid(productId);
        MallHistory checkMallHistory;
        checkMallHistory = mallHistoryMapper.selectByUserIdAndProductId(userId, productId);
        if(checkMallHistory == null) {
            mallHistoryMapper.myInsert(mallHistory);
        } else {
            mallHistoryMapper.myUpdate(mallHistory);
        }
    }


    public ServerResponse<String> listProductContent(Integer productId) {

        return ServerResponse.createBySuccess(mallProductMapper.selectContentById(productId));
    }

    //后台更新销量
    //根据mall_order_item 表中的相同product_id进行相加
    public ServerResponse updateSalesVolume() {

        //查询所有交易成功的订单编号 BigInt 类型的编号
        List<BigInteger> succssMallOrderList = mallOrderMapper.listSuccessOrderNo(SUCCESS);

        //得到product_id 和sales_volume
        List<Map<String, Object>> mallOrderItemList = mallOrderItemMapper.listGroupByProductId(succssMallOrderList);

        //存储产品id
        List<Integer> mallProductIdList = new ArrayList<>();

        for(Map<String, Object> mallOrderItem : mallOrderItemList){
            int productId = (int) mallOrderItem.get("productId");
            int sumQuantity = ((BigDecimal) mallOrderItem.get("sumQuantity")).intValue();
            mallProductIdList.add(productId);
        }
        //批量查询出要更新的销量数据库
        List<MallHot> mallHotList = mallHotMapper.batchListHot(mallProductIdList);
            for(int i = 0; i < mallProductIdList.size(); i++){
                MallHot mallHot = mallHotList.get(i);
                mallHot.setSalesVolume(((BigDecimal)mallOrderItemList.get(i).get("sumQuantity")));
                mallHotList.set(i, mallHot);
                mallHotMapper.updateHot(mallHot);
            }
            return ServerResponse.createBySuccess();
        }
}
